package com.turing.data.controller;

import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.turing.common.response.ResponseCode;
import com.turing.common.response.ResponseMessage;
import com.turing.common.response.ResponseVO;
import com.turing.common.util.AssertUtil;
import com.turing.common.util.ResponseUtil;
import com.turing.common.util.SimilarityUtil;
import com.turing.data.inner.FileTaskInnerService;
import com.turing.data.inner.TaskRecordInnerService;
import com.turing.data.model.dto.produre.TaskRecordDto;
import com.turing.data.model.vo.produre.TaskRecordVo;
import com.turing.data.service.element.ElementService;
import com.turing.data.service.review.ReviewService;
import com.turing.data.vo.in.review.ElementSimpleSearchVO;
import com.turing.data.vo.in.review.FileSearchVO;
import com.turing.data.vo.in.review.ReviewRequestVO;
import com.turing.data.vo.in.review.ScrollSearchVO;
import com.turing.data.vo.out.review.DrawFileVO;
import com.turing.data.vo.out.review.TaskElementVO;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("review")
public class ReviewController {

    @Value("${fdfs.domain}")
    private String MEDIA_PATH;

    @Value("${answer.path}")
    private String ANSWER_PATH;

    @Value("${groovy.script.path}")
    private String GROOVY_PATH;

    @Autowired
    private FastFileStorageClient dfsClient;

    @Autowired
    private ReviewService reviewService;

    @Autowired
    private TaskRecordInnerService taskRecordInnerService;

    private Log logger = LogFactory.getLog(ReviewController.class);

    /*
     * 对外-请求数据审核接口
     * */
    @PostMapping("requireReview")
    public ResponseVO<String> requireReview(@RequestBody ReviewRequestVO requestVO) {
        return new ResponseVO<>();
    }

    /*
     * 对内-获取任务要素结果
     * */
    @PostMapping("getTaskElements")
    public ResponseVO<Object> getTaskElements(@RequestBody ElementSimpleSearchVO searchVO) {
        logger.info(">>>>>>>>>>>>>>>> getting task elements ");
        return ResponseUtil.success(reviewService.getTaskElements(searchVO));
    }

    /*
     * 对内-获取任务要素结果
     * */
    @PostMapping("getModelElements")
    public ResponseVO<Object> getModelElements(@RequestBody ElementSimpleSearchVO searchVO) {
        logger.info(">>>>>>>>>>>>>>>> getting model result ");
        return ResponseUtil.success(reviewService.getModelElements(searchVO));
    }

    @PostMapping("runScriptsTask")
    public ResponseVO<String> runScriptsTask(@RequestParam("parentTaskSn") String taskSn) {
        return new ResponseVO<>(reviewService.runScriptsTask(taskSn), ResponseCode.SUCCESS, ResponseMessage.SUCCESS, 1);
    }

    @PostMapping("getTaskElementsScroll")
    public ResponseVO<Object> getTaskElement(@RequestBody ScrollSearchVO scrollSearchVO) {
        return ResponseUtil.success(reviewService.getTaskElementsScroll(scrollSearchVO));
    }

    /**
     * 从主场景复制数据
     *
     * @param taskSn    主场景任务id
     * @param newTaskSn 子场景任务id
     * @return com.turing.common.response.ResponseVO<java.lang.Boolean>
     * @author lcy
     * @date 2021/6/16 10:42
     **/
    @PostMapping("copyTaskContent")
    public ResponseVO<Boolean> copyTaskContent(@RequestParam String taskSn, @RequestParam String newTaskSn) {
        return ResponseUtil.success(reviewService.copyTaskContent(taskSn, newTaskSn));
    }

    /**
     * 文件名后缀前添加一个时间戳
     */
    private String getFileName(String fileName) {
        int index = fileName.lastIndexOf(".");
        final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyymmddHHmmss");  //设置时间格式
        String nowTimeStr = sDateFormate.format(new Date()); // 当前时间
        fileName = fileName.substring(0, index) + "_" + nowTimeStr + fileName.substring(index);
        return fileName;
    }


    @PostMapping("upload")
    public String coon(@RequestParam String path) {
        File originFile = new File(path);
        String originFilePath = uploadFileToDFS(originFile);
        originFilePath = MEDIA_PATH + originFilePath;
        return originFilePath;
    }

    private Map<String, Map<String, String>> list2Json(List<List<Object>> lists) {
        Map<String, Map<String, String>> map = new HashMap<>();
        List<Object> objectsName = lists.get(0);
        for (int i = 1; i < lists.size(); i++) {
            List<Object> objectsValue = lists.get(i);
            int size = objectsName.size();
            Map<String, String> mapNew = new HashMap<>();
            for (int j = 0; j < size; j++) {
                mapNew.put(objectsName.get(j).toString(), objectsValue.get(j).toString());
            }
            map.put(objectsValue.get(0).toString(), mapNew);
        }
        return map;
    }

    synchronized private String uploadFileToDFS(File file) {
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            StorePath storePath = dfsClient.uploadFile(fileInputStream, fileInputStream.available(), "json", null);
            return storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 刷数，将旧的数据执行groovy脚本落入数据库
     *
     * @return com.turing.common.response.ResponseVO<java.lang.Object>
     * @author lcy
     * @date 2021/8/9 10:07
     **/
    @ApiOperation(value = "跑旧数据脚本")
    @GetMapping("runScriptsTask")
    public ResponseVO<Object> runScriptsTask() {
        TaskRecordDto taskRecordDto = TaskRecordDto.builder().build();
        List<String> taskSns = taskRecordInnerService.getTaskRecord(taskRecordDto).getData().stream().map(TaskRecordVo::getTaskSn).collect(Collectors.toList());
        taskSns.forEach(this::runScriptsTask);
        return ResponseUtil.success();
    }

}
